package com.compass.mobile.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.AvtivitySearchDoctorDeptBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.DepartmentBean
import com.compass.mobile.models.Doctor
import com.compass.mobile.presenters.DepartmentPresenter
import com.compass.mobile.presenters.DoctorPresenter
import com.compass.mobile.ui.viewModel.DoctorViewModel
import com.compass.mobile.widget.MyBridgeAdapter

/**
 * Description：搜索科室和医生
 * Date:2024/7/4 16:16
 */
class SearchDoctorAndDepartmentActivity : BaseVBActivity<AvtivitySearchDoctorDeptBinding>() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, SearchDoctorAndDepartmentActivity::class.java)
            context.startActivity(intent)
        }
    }

    private var keyWords: String? = null
    private val doctorViewModel: DoctorViewModel by viewModels()
    private var doctors: MutableList<Doctor> = mutableListOf()

    private var depts: MutableList<DepartmentBean>  = mutableListOf()
    private lateinit var arrayDoctorAdapter: ArrayObjectAdapter
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    private var isFirst = true

    override fun initView(savedInstanceState: Bundle?) {
//        FocusViewUtils.scaleView(mBinding.edtKeyWords, 0)
        initSpecialColumn()
        mBinding.caseDept.post {
            // 使用获取到的宽度
            val width = mBinding.caseDept.width
            specialColumn(width)
        }
        mBinding.edtKeyWords.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //点击了搜索按钮后，需要隐藏软键盘
                keyWords = mBinding.edtKeyWords.text.toString().trim()
                getRecommendDoctor()

            }
            false
        }


//        mBinding.edtKeyWords.textChangeFlow()
//            .distinctUntilChanged()
//            .debounce(500)
//            .flowOn(Dispatchers.IO)
//            .onEach {
//                //这里走查询接口
//                keyWords = mBinding.edtKeyWords.text.toString().trim()
//                getRecommendDoctor()
//            }
//            .launchIn(lifecycleScope)
        mBinding.edtKeyWords.requestFocus()
    }


    private fun getRecommendDoctor() {
        doctorViewModel.searchDept(keyWords)
    }

    override fun initData() {
//        showLoading()
//        getRecommendDoctor()
        doctorViewModel.doctorsLiveData.observe(this) {
            dismissLoading()
            it?.let {doctorsList->
                doctors = doctorsList
                arrayDoctorAdapter.clear()
                arrayDoctorAdapter.addAll(0, doctors)
            }


            setEmptyView()
        }
        doctorViewModel.departmentListLiveData.observe(this){
            it?.let { list ->
                depts = list
                arrayObjectAdapter.clear()
                arrayObjectAdapter.addAll(0, depts)
            }
            doctorViewModel.searchDoctors(keyWords)

        }

    }



    private fun setEmptyView() {
        if (doctors.isNullOrEmpty()&&depts.isNullOrEmpty()) {
            mBinding.emptyView.visible()
        } else {
            mBinding.emptyView.gone()
        }


    }


    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item = doctors?.get(position)
            item?.department?.let {
                DoctorHomePageActivity.start(this@SearchDoctorAndDepartmentActivity, item.id, it)
            }


        }
    }


    @SuppressLint("RestrictedApi")
    fun initSpecialColumn() {
        mBinding.caseItem.verticalSpacing = dpToPx(10)
        val doctorPresenter = DoctorPresenter("2")
        arrayDoctorAdapter = ArrayObjectAdapter(doctorPresenter)
        val itemBridgeAdapter = MyBridgeAdapter(
            this,
            arrayDoctorAdapter, onItemClickListener
        )
        mBinding.caseItem.setAdapter(itemBridgeAdapter)
        mBinding.caseItem.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayDoctorAdapter.addAll(0, doctors)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )

    }

    private val onDeptItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item = depts[position]
            item?.let {
                DepartmentIntroductionActivity.start(this@SearchDoctorAndDepartmentActivity,it.id,item.code,"inquiry")
            }
        }
    }

    @SuppressLint("RestrictedApi")
    fun specialColumn(width: Int) {
        mBinding.caseDept.setNumColumns(2)
        mBinding.caseDept.horizontalSpacing = dpToPx(10)
        mBinding.caseDept.verticalSpacing = dpToPx(10)
        val finalWidth = width - dpToPx(40)
        val departmentPresenter = DepartmentPresenter()
        departmentPresenter.setFinalWidth(finalWidth / 2)
        arrayObjectAdapter = ArrayObjectAdapter(departmentPresenter)
        val itemBridgeAdapter = MyBridgeAdapter(
            this,
            arrayObjectAdapter, onDeptItemClickListener
        )
        mBinding.caseDept.setAdapter(itemBridgeAdapter)
        mBinding.caseDept.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, depts)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )

    }

}
